import re
import htmlentitydefs
from datetime import tzinfo, timedelta
from django.conf import settings


# Stolen from Trac - util/datefmt.py
_zero = timedelta(0)

class FixedOffset(tzinfo):
    """Fixed offset in minutes east from UTC."""

    def __init__(self, offset, name):
       self._offset = timedelta(minutes=offset)
       self.zone = name

    def __str__(self):
       return self.zone

    def __repr__(self):
       return '<FixedOffset "%s" %s>' % (self.zone, self._offset)

    def utcoffset(self, dt):
       return self._offset

    def tzname(self, dt):
       return self.zone

    def dst(self, dt):
       return _zero

utc = FixedOffset(0, "UTC")


reduceLink = settings.URL_SHORTENER

class CustomAsUlFormMixin:
    def as_ul(self):
        """The same as standard but encloses help text in <p class="help">%s</p>"""
        return self._html_output(u'<li>%(errors)s%(label)s %(field)s%(help_text)s</li>', u'<li>%s</li>', '</li>', u'<p class="help">%s</p>', False)



def unescape(text, encoding="UTF-8"):
    """
    Removes HTML or XML character references and entities from a text string.

    @param text The HTML (or XML) source text.
    @return The unescaped text as a Unicode.

    From http://python.org.ar/pyar/Recetario/DecodeHtmlEntities - Thanks Martin Conte Mac Donell
    """

    def fixup(m):
        text = m.group(0)
        if text[:2] == "&#":
            # character reference
            try:
                if text[:3] == "&#x":
                    text = unichr(int(text[3:-1], 16))
                else:
                    text = unichr(int(text[2:-1]))
            except ValueError:
                pass
        else:
            # named entity
            try:
                text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
            except KeyError:
                pass

        return text

    # Decode string as needed
    text = text.decode(encoding) if isinstance(text, str) else text
    return text and re.sub("&#?\w+;", fixup, text)


p = re.compile('(<p.*?>)|(<tr.*?>)', re.I)
t = re.compile('<td.*?>', re.I)
comm = re.compile('<!--.*?-->', re.M)
tags = re.compile('<.*?>', re.M)

# From: http://snippets.dzone.com/posts/show/2898
def html2txt(s):
    """Convert the html to raw txt
    - suppress all return
    - <p>, <tr> to return
    - <td> to tab
    Need the foolwing regex:
    p = re.compile('(<p.*?>)|(<tr.*?>)', re.I)
    t = re.compile('<td.*?>', re.I)
    comm = re.compile('<!--.*?-->', re.M)
    tags = re.compile('<.*?>', re.M)
    version 0.0.1 20020930
    """
    s = s.replace('\n', '') # remove returns time this compare to split filter join
    s = p.sub('\n', s) # replace p and tr by \n
    s = t.sub('\t', s) # replace td by \t
    s = comm.sub('', s) # remove comments
    s = tags.sub('', s) # remove all remaining tags
    s = re.sub(' +', ' ', s) # remove running spaces this remove the \n and \t
    # handling of entities
    result = s
    return result

